package myspringmvc.listener;

import ioc.BeanFactory;
import ioc.ClassPathXmlApplicationContext;
import myspringmvc.ViewBaseServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 对应ioc actor
 */
@WebServlet("/listener_test.do")
public class DispatcherServlet extends ViewBaseServlet {

    private BeanFactory beanFactory;

    @Override
    public void init() throws ServletException {
        super.init();
        this.beanFactory = (BeanFactory) getServletContext().getAttribute("beanFactory");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String servletPath = req.getServletPath();
        servletPath = servletPath.substring(1);
        int lastIndexOf = servletPath.lastIndexOf(".do");
        servletPath = servletPath.substring(0, lastIndexOf);
        Object obj = beanFactory.getBeans(servletPath);

        req.setCharacterEncoding("utf-8");
        String operate = req.getParameter("operate");
        if (operate == null || "".equals(operate)) {
            operate = "index";
        }
        try {
            Method[] methods = obj.getClass().getDeclaredMethods();
            for (Method method: methods) {
                //获取参数
                if (operate.equals(method.getName())) {
                    Parameter[] parameters = method.getParameters();
                    Object[] parameterValues = new Object[parameters.length];
                    for (int i = 0; i < parameters.length; i++) {
                        Parameter parameter = parameters[i];
                        String name = parameter.getName();
                        if ("request".equals(name)) {
                            parameterValues[i] = req;
                        } else if ("response".equals(name)) {
                            parameterValues[i] = resp;
                        } else if ("session".equals(name)) {
                            parameterValues[i] = req.getSession();
                        } else {
                            String reqParameter = req.getParameter(name);
                            Class<?> parameterType = parameter.getType();
                            Object parameterObj = reqParameter;
                            if (parameterObj != null) {
                                if (parameterType.equals("java.lang.Integer")) {
                                    parameterObj = Integer.parseInt(reqParameter);
                                }
                            }

                            parameterValues[i] = parameterObj;
                        }
                    }
                    //方法调用
                    method.setAccessible(true);
                    Object invoke = method.invoke(obj, parameterValues);
                    /**
                     * 统一处理返回操作
                     */
                    if (invoke != null) {
                        String invoke1 = (String) invoke;
                        boolean b = invoke1.startsWith("redirect:");
                        if (b) {
                            String uri = invoke1.substring("redirect:".length());
                            resp.sendRedirect(uri);
                        } else {
                            if (invoke1.equals("error")) {
                                System.out.println("error!!!");
                            } else {
                                super.processTemplate(invoke1,req,resp);
                            }
                        }
                    }
                }
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
